import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import base from "@src/store/base";
import dayjs from "dayjs";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor'],
  }],
  properties: {},
  data: {
    beginDay: "",
    endDay: "",
    displayList: []
  },
  methods: {
    onLoad(options) {
      let beginDay = options.beginDay;
      let endDay = options.endDay;
      this.setData({
        beginDay: beginDay,
        endDay: endDay
      })
      this.initCalender();
    },
    initCalender() {
      let thisMonth = dayjs().startOf('month')
      let displayList = []
      displayList.push(this.getMonthData(thisMonth));
      displayList.push(this.getMonthData(thisMonth.add(1, 'month')));
      displayList.push(this.getMonthData(thisMonth.add(2, 'month')));
      displayList.push(this.getMonthData(thisMonth.add(3, 'month')));
      this.setData({today: dayjs().format('YYYY-MM-DD'), displayList: displayList})
    },

    getMonthData(day) {
      let cur = dayjs(day).startOf('month')
      let end = dayjs(day).endOf('month')

      let title = cur.format("YYYY-MM")
      // 星期
      let startPlaceholder = cur.day()
      let endPlaceholder = 7 - end.day()
      let days = []
      while (cur.isBefore(end) || cur.isSame(end)) {
        days.push({
          year: cur.year(),
          month: cur.month(),
          day: cur.date(),
          str: cur.format("YYYY-MM-DD")
        })
        cur = cur.add(1, 'day');
      }
      return {title, startPlaceholder, days, endPlaceholder};
    },
    handleSelect(e) {
      let selectDayStr = e.currentTarget.dataset.day;
      if (selectDayStr < this.data.today) {
        return;
      }
      if (this.data.endDay && this.data.beginDay) {
        // 重新选择
        this.setData({beginDay: selectDayStr, endDay: null})
        return;
      }

      if (!this.data.endDay) {
        let beginDay = dayjs(this.data.beginDay, 'YYYY-MM-DD')
        let endDay = dayjs(selectDayStr, 'YYYY-MM-DD')
        if (endDay.isBefore(beginDay) || endDay.isSame(beginDay)) {
          this.setData({beginDay: selectDayStr});
          return;
        }
        this.setData({endDay: selectDayStr})
      }
    },
    handleConfirm() {
      if (!this.data.endDay) {
        wx.showToast({title: "请选择离店时间", icon: 'none', duration: 4000})
        return;
      }
      let beginDay = dayjs(this.data.beginDay, 'YYYY-MM-DD')
      let endDay = dayjs(this.data.endDay, 'YYYY-MM-DD')
      if (endDay.diff(beginDay, 'day') > 28) {
        wx.showToast({title: "选择的时间不能超过28天", icon: 'none', duration: 4000})
        return;
      }
      const eventChannel = this.getOpenerEventChannel()
      if (eventChannel) {
        eventChannel.emit('selectDay', {beginDay: this.data.beginDay, endDay: this.data.endDay});
      }
      wx.navigateBack();
    }
  }
})
